package com.example.fechat.utils

import android.content.Context
import com.example.fechat.bean.MessageBean
import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVParser
import org.apache.commons.csv.CSVPrinter
import java.io.*

object CSVUtils {

    fun getPath(context: Context, userId: String): String {
        return "${context.getExternalFilesDir(null)}/message/${userId}.csv"
    }

    fun writeToCSV(bean: MessageBean, path: String) {
        val bufferWrite = BufferedWriter(OutputStreamWriter(FileOutputStream(path, true)))
        val csvPrinter = CSVPrinter(bufferWrite, CSVFormat.DEFAULT)
        val data = listOf(
            bean.message,
            bean.userName,
            bean.isResponse,
            bean.time,
            bean.isSuccess,
            bean.messageType
        )
        csvPrinter.printRecord(data)
        csvPrinter.flush()
        csvPrinter.close()
    }

    fun readFromCSV(path: String): ArrayList<MessageBean> {
        val bufferedReader = BufferedReader(FileReader(File(path)))
        val csvParser = CSVParser(bufferedReader, CSVFormat.DEFAULT)
        val messageBeans = ArrayList<MessageBean>()
        csvParser.forEach { parse ->
            val messageBean = MessageBean(
                parse[0],
                parse[1],
                parse[2].toBoolean(),
                parse[3].toLong(),
                parse[4].toBoolean(),
                parse[5]
            )
            messageBeans.add(messageBean)
        }
        return messageBeans
    }
}